package top.kaoshanji.p3ch13a;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import top.kaoshanji.u1constant.FileConstant;

import javax.crypto.*;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * 代码清单-p3ch13a-427页a：使用加密方式保存对象序列化之后的内容
 * author kaoshanji
 * ^_^
 * create time 2025/2/8 17:47
 */
public class StoreObject {

    private static final Logger logger = LogManager.getLogger(StoreObject.class);

    public static void main(String[] args) throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IOException {
        logger.info("...代码清单-p3ch13a-427页a：使用加密方式保存对象序列化之后的内容...");

        StoreObject so = new StoreObject();
        KeyGenerator generator = KeyGenerator.getInstance("DES");
        SecretKey key = generator.generateKey();
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.ENCRYPT_MODE, key);

        so.storeSafely("Hello World", cipher, Paths.get(FileConstant.LOCAL_ROOT_PATH.concat("p3ch13a427页a\\saved.obj")));
    }

    public void storeSafely(Serializable obj, Cipher cipher, Path path) throws IOException {
        try (ObjectOutputStream oos = new ObjectOutputStream(new CipherOutputStream(Files.newOutputStream(path), cipher))){
            oos.writeObject(obj);
        }

    }

}
